package com.tchcn.cashier.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fanwe.library.adapter.http.model.SDResponse;
import com.othershe.nicedialog.BaseNiceDialog;
import com.tchcn.cashier.R;
import com.tchcn.cashier.dialog.ChooseCircleDialog;
import com.tchcn.cashier.dialog.ChooseCityDialog;
import com.tchcn.cashier.dialog.ChooseIndustryDialog;
import com.tchcn.cashier.order.dialog.ChooseNumDialog;
import com.tchcn.library.http.AppRequestCallback;
import com.tchcn.library.utils.SDToast;
import com.tchcn.library.utils.SDViewUtil;
import com.zhy.autolayout.AutoLayoutActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.tchcn.library.common.CommonInterface;
import com.tchcn.library.model.BaseActModel;

import org.json.JSONException;
import org.json.JSONObject;

public class RegisterActivity extends AutoLayoutActivity  implements Handler.Callback {

    @BindView(R.id.tv_progress1)
    TextView tvProgress1;//圆圈
    @BindView(R.id.view1)
    View view1;//过程线
    @BindView(R.id.tv_progress2)
    TextView tvProgress2;
    @BindView(R.id.view2)
    View view2;
    @BindView(R.id.tv_progress3)
    TextView tvProgress3;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;//获取验证码
    @BindView(R.id.iv_empty_code)
    ImageView ivEmptyCode;//清空号码
    @BindView(R.id.et_phone)
    EditText etPhone;//手机号
    @BindView(R.id.et_code)
    EditText etCode;//验证码
    @BindView(R.id.ll_progress1)
    LinearLayout llProgress1;
    @BindView(R.id.et_account)
    EditText etAccount;//账号
    @BindView(R.id.et_password)
    EditText etPassword;//密码
    @BindView(R.id.ll_progress2)
    LinearLayout llProgress2;
    @BindView(R.id.et_bus_name)
    EditText etBusName;//商户名称
    @BindView(R.id.iv_empty_name)
    ImageView ivEmptyName;//清空商户
    @BindView(R.id.tv_bus_type)
    TextView tvBusType;//所属行业
    @BindView(R.id.tv_bus)
    TextView tvBus;//所属业态
    @BindView(R.id.et_store_name)
    EditText etStoreName;//门店名称
    @BindView(R.id.iv_empty_store_name)
    ImageView ivEmptyStoreName;//清空门店
    @BindView(R.id.tv_bus_circle)
    TextView tvBusCircle;//所属商圈
    @BindView(R.id.iv_empty_address)
    ImageView ivEmptyAddress;//清除地址
    @BindView(R.id.ll_progress3)
    LinearLayout llProgress3;
    @BindView(R.id.btn_next)
    Button btnNext;//下一步
    @BindView(R.id.tv_city)
    TextView tvCity;//选择城市
    @BindView(R.id.et_address)
    EditText etAddress;//详细地址


    private boolean pass1 = false;//第一部是否完成
    private boolean pass2 = false;//第二部~~

    private static final int SENDSMS = 0;
    public int timer = 60;
    public Handler handler;
    //验证码
    String code;

    private String user_id;
    private String qu_id;
    private String cate_id;
    private String deal_cate_id;
    private String quan_id;
    private String city_id;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        tvGetCode.setEnabled(false);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString()))
                    ivEmptyCode.setVisibility(View.VISIBLE);
                else
                    ivEmptyCode.setVisibility(View.GONE);

                if(editable.toString().length() == 11){
                    tvGetCode.setTextColor(getResources().getColor(R.color.item_name));
                    tvGetCode.setEnabled(true);
                }else {
                    tvGetCode.setEnabled(false);
                    tvGetCode.setTextColor(getResources().getColor(R.color.color_hint));
                }
            }
        });

        etBusName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString()))
                    ivEmptyName.setVisibility(View.VISIBLE);
                else
                    ivEmptyName.setVisibility(View.GONE);

            }
        });

        etStoreName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString()))
                    ivEmptyStoreName.setVisibility(View.VISIBLE);
                else
                    ivEmptyStoreName.setVisibility(View.GONE);

            }
        });

        etAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString()))
                    ivEmptyAddress.setVisibility(View.VISIBLE);
                else
                    ivEmptyAddress.setVisibility(View.GONE);

            }
        });

        handler = new Handler(this);
    }



    @OnClick({R.id.rl_title, R.id.tv_get_code, R.id.iv_empty_code, R.id.iv_empty_name, R.id.ll_bus_type, R.id.ll_bus, R.id.iv_empty_store_name, R.id.ll_bus_circle, R.id.iv_empty_address, R.id.btn_next,R.id.ll_city})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_title:
                this.finish();
                break;
            case R.id.tv_get_code:
                tvGetCode.setEnabled(false);
                tvGetCode.setText("发送中");
                String phone = etPhone.getText().toString();
                if (phone.isEmpty()) {
                    SDToast.showToast("手机号不能为空");
                    return;
                }
                CommonInterface.getValidCode(phone,new AppRequestCallback<BaseActModel>() {
                    @Override
                    protected void onSuccess(SDResponse sdResponse) {
                        SDToast.showToast("发送成功");
                        code = sdResponse.getResult();
                        tvGetCode.setText(timer + "s");
                        handler.sendEmptyMessageDelayed(SENDSMS, 1000);
                    }

                    @Override
                    protected void onError(SDResponse resp) {
                        super.onError(resp);
                        tvGetCode.setEnabled(true);
                        tvGetCode.setText("重新发送");
                        SDToast.showToast("发送失败，请检查网络连接");
                    }
                });
                break;
            case R.id.iv_empty_code:
                etPhone.setText("");
                break;
            case R.id.iv_empty_name:
                etBusName.setText("");
                break;
            case R.id.ll_bus_type:
                final ChooseIndustryDialog industryDialog = ChooseIndustryDialog.newInstance(0,null);
                industryDialog.setConvertListener(new ChooseNumDialog.OnDialogClickListener() {
                    @Override
                    public void onItemClick(View view, BaseNiceDialog dialog) {
                        tvBusType.setText(industryDialog.getSelectIndustry().getName());
                        deal_cate_id = industryDialog.getSelectIndustry().getId();
                        tvBusType.setTextColor(getResources().getColor(R.color.item_name));
                        dialog.dismiss();
                    }
                }).setWidth(714)
                        .show(getSupportFragmentManager());
                break;
            case R.id.ll_bus:
                final ChooseIndustryDialog industryDialog2 = ChooseIndustryDialog.newInstance(1,deal_cate_id);
                industryDialog2.setConvertListener(new ChooseNumDialog.OnDialogClickListener() {
                    @Override
                    public void onItemClick(View view, BaseNiceDialog dialog) {
                        tvBus.setText(industryDialog2.getSelectIndustry().getName());
                        cate_id = industryDialog2.getSelectIndustry().getId();
                        tvBus.setTextColor(getResources().getColor(R.color.item_name));
                        dialog.dismiss();
                    }
                }).setWidth(714)
                        .show(getSupportFragmentManager());
                break;
            case R.id.iv_empty_store_name:
                etStoreName.setText("");
                break;
            case R.id.ll_bus_circle:
                final ChooseCircleDialog chooseCircleDialog = ChooseCircleDialog.newInstance(city_id);
                chooseCircleDialog.setConvertListener(new ChooseNumDialog.OnDialogClickListener() {
                    @Override
                    public void onItemClick(View view, BaseNiceDialog dialog) {
                        tvBusCircle.setText(chooseCircleDialog.getCommercialArea().getArea_name());
                        quan_id= chooseCircleDialog.getCommercialArea().getId();
                        tvBusCircle.setTextColor(getResources().getColor(R.color.item_name));
                        dialog.dismiss();
                    }
                }).setWidth(714)
                        .show(getSupportFragmentManager());
                break;
            case R.id.iv_empty_address:
                etAddress.setText("");
                break;
            case R.id.ll_city:
                //选择城市
                final ChooseCityDialog cityDialog = ChooseCityDialog.newInstance();
                cityDialog.setConvertListener(new ChooseNumDialog.OnDialogClickListener() {
                    @Override
                    public void onItemClick(View view, BaseNiceDialog dialog) {
                        if (view.getId() == R.id.tv_commit) {
                            city_id = cityDialog.getCityId();
                            qu_id  =cityDialog.getQuId();
                            tvCity.setText(cityDialog.getCityInfo());
                            tvCity.setTextColor(getResources().getColor(R.color.item_name));
                            dialog.dismiss();
                        }
                    }
                }).setWidth(SDViewUtil.px2dp(714))
                        .show(getSupportFragmentManager());
                break;
            case R.id.btn_next:
               if(!pass1){
                   //验证码正确则显示下一步
                   if(etCode.getText().toString().trim().equals(code)){
                       pass1 = true;
                       llProgress1.setVisibility(View.GONE);
                       llProgress2.setVisibility(View.VISIBLE);
                       tvProgress1.setBackgroundResource(R.drawable.register_circle_bg_checked);
                       tvProgress1.setTextColor(getResources().getColor(R.color.white));
                   }else{
                       SDToast.showToast("验证码错误");
                   }
               }else if(!pass2){

                   String account = etAccount.getText().toString();
                   String password = etPassword.getText().toString();
                   if (account.isEmpty()||password.isEmpty()) {
                       SDToast.showToast("帐号密码不能为空");
                       return;
                   }
                   CommonInterface.register(account,password,etPhone.getText().toString(),code,new AppRequestCallback<BaseActModel>() {
                       @Override
                       protected void onSuccess(SDResponse sdResponse) {
                           if("200".equals(actModel.getCode())) {
                               pass2 = true;
                               llProgress2.setVisibility(View.GONE);
                               llProgress3.setVisibility(View.VISIBLE);
                               tvProgress2.setBackgroundResource(R.drawable.register_circle_bg_checked);
                               tvProgress2.setTextColor(getResources().getColor(R.color.white));
                            /*ViewGroup.LayoutParams params=view.getLayoutParams();
                           params.height=3;
                           view2.setLayoutParams(params);*/
                               btnNext.setText("完成注册");
                               try {
                                   JSONObject jsonObject = new JSONObject(sdResponse.getResult()).getJSONObject("data");
                                   user_id =jsonObject.getString("id");
                               } catch (JSONException e) {
                                   e.printStackTrace();
                               }

                           }else {
                               SDToast.showToast(actModel.getMsg());
                           }
                       }

                   });



               }else{
                   CommonInterface.addSupplier(etBusName.getText().toString(), user_id, qu_id, etAddress.getText().toString()
                           , cate_id, deal_cate_id, quan_id, city_id, new AppRequestCallback<BaseActModel>() {
                               @Override
                               protected void onSuccess(SDResponse sdResponse) {
                                   SDToast.showToast(actModel.getMsg());
                                   finish();
                               }
                           });
               }
                break;

        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case SENDSMS:
                if (timer > 0) {
                    timer--;
                    tvGetCode.setText(timer + "s");
                    handler.sendEmptyMessageDelayed(SENDSMS, 1000);
                } else {
                    timer = 60;
                    tvGetCode.setText("重新获取");
                    tvGetCode.setEnabled(true);
                }
                break;
        }
        return false;
    }


}
